/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Listeners;

import Listeners.SettingsListener.Comm;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.EnumSet;
import shutdown.AutoShutDown;
import shutdown.SwingIO;

/**
 *
 * @author Joel
 */
public class SettingsListener implements ActionListener {

    public static final String TIME_NOW = "HH:mm:ss";
    public static final String DATE_AND_TIME = "yyyy-MM-dd HH:mm:ss";
    private static final String SET_TIME = "at time";
    private static final String UNTIL = "after amount time";

    enum Comm {
	HIB ("hibernate", "/h"),
	SD ("shutdown", "/s"),
	SD_R ("shutdown & restart", "/r"),
	FCA ("force close apps", "/t 1"),
	LOGOFF ("logoff", "/l");

        private final String ourname, comm;
	Comm(String name, String comm) {
            this.ourname  = name;
            this.comm = comm;
	}
	
	public String getComm() { return comm; }
	public String toString() { return ourname; }
	};

    long delay = 0;
    String time = null;
    private final int[] MAX_VALS = {23, 59, 59};
    private Timer timer = new Timer();
    private boolean canRun = false;

    private static final SettingsListener sl = new SettingsListener();

    private SettingsListener() {};

    public static SettingsListener getInstance() {
        return sl;
        }

    public void actionPerformed(ActionEvent e) {
        String[] action = e.getActionCommand().split(":");
        if (action[0].equalsIgnoreCase(SET_TIME)) {
            try {
                time = SwingIO.inputMsg("Enter time in format hh:mm:ss", "Enter time");
            } catch (NullPointerException ex) {
                System.out.println("Timer reset");
                timer.cancel();
                timer = new Timer();
                }
            time = time.trim();
            String current = AutoShutDown.currentTime(TIME_NOW);
            String[] toStop = time.split(":"), rightNow = current.split(":");
            time = null;
            for (int i = 0; i < toStop.length; i++) {
                if (!Character.isDigit(toStop[i].charAt(0))) {
                    SwingIO.errorMsg("Invalid Format");
                    return;
                    }
                }
            switch (toStop.length) {
                case 3:
                    int sec = 0,
                     curr = 0;
                    for (int k = 1, i = 2; i >= 0; k *= 60, i--) {
                        int val = Math.min(Integer.parseInt(toStop[i]), MAX_VALS[i]);
                        time = time != null ? val + ":" + time : String.valueOf(val);
                        sec += val * k;
                        curr += Math.min(Integer.parseInt(rightNow[i]), MAX_VALS[i]) * k;
                        }
                    delay = (sec - curr) * 1000;
                    canRun = true;
                    break;
                default:
                    timer.cancel();
                    timer = new Timer();
                }
            }
        if (action[0].equalsIgnoreCase(UNTIL)) {
            try {
                time = SwingIO.inputMsg("Enter time to wait (hh:mm)", "Time Until");
            } catch (NullPointerException ex) {
                System.out.println("Timer reset");
                timer.cancel();
                timer = new Timer();
                }
            time = time.trim();
            String[] toStop = time.split(":");
            time = null;
            for (int i = 0; i < toStop.length; i++) {
                if (!Character.isDigit(toStop[i].charAt(0))) {
                    SwingIO.errorMsg("Invalid Format");
                    return;
                    }
                }
            switch (toStop.length) {
                case 1:
                    int val = Integer.parseInt(toStop[0]);
                    delay = val * 60000;
                    break;
                case 2:
                    int hr = Integer.parseInt(toStop[0]),
                     min = Integer.parseInt(toStop[1]);
                    delay = min * 60000 + hr * 3600000;
                    break;
                default:
                    timer.cancel();
                    timer = new Timer();
                    System.out.println("Timer Reset");
                    return;
                }
            time = toStop.length > 1 ? "time delay(" + toStop[0] + ":" + toStop[1] + ")" : "time delay(" + toStop[0] + ")";
            canRun = true;
            }
	for(Comm c : EnumSet.range(Comm.HIB, Comm.LOGOFF))
            if (action[1].equalsIgnoreCase(c.toString()))
                if (canRun) {
                    setEvent(c, delay, action[1] + " @ " + time, e);
                    System.err.println(timer);
                    return;
                }
        }

    private void setCurrentMsg(String msg, ActionEvent e) {
        MenuItem item = (MenuItem) e.getSource();
        PopupMenu mainmenu = (PopupMenu) ((Menu) (item.getParent())).getParent();
        Menu currentMenu = (Menu) mainmenu.getItem(3);
        currentMenu.removeAll();
        currentMenu.add(msg);
        }

    private void setEvent(Comm choice, long delay, String msg, ActionEvent e) {
        timer.schedule(new Shutdown(choice), delay);
        System.out.println("Time set to: " + time);
        canRun = false;
        setCurrentMsg(msg, e);        
        }

    private class Shutdown extends TimerTask {

        private String mod;

        public Shutdown(Comm t) {
            super();
            mod = t.getComm();
        }

        @Override
        public void run() {
            Process child = null;
            try {
                child = Runtime.getRuntime().exec("shutdown " + mod);
            }
            catch (IOException ex) {}
        }
    }

    }

